﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ERP.ERPSystem.ProductionSystem
{
    /// <summary>
    /// 车间设置服务类，实现了 IWorkshopServer 接口中定义的业务逻辑
    /// </summary>
    public class WorkshopServer : ApplicationService, IWorkshopServer
    {
        /// <summary>
        /// 车间设置仓储
        /// </summary>
        private readonly IRepository<Workshop, int> _workshopRepository;
        
        /// <summary>
        /// 构造函数，通过依赖注入获取车间仓储的实例
        /// </summary>
        /// <param name="workshopRepository">由DI容器提供的车间仓储接口</param>
        public WorkshopServer(IRepository<Workshop, int> workshopRepository)
        {
            _workshopRepository = workshopRepository;
        }

        /// <summary>
        /// 根据ID获取单个车间信息
        /// </summary>
        /// <param name="id">车间实体的ID</param>
        /// <returns>返回找到的车间DTO</returns>
        public async Task<WorkshopDTO> GetAsync(int id)
        {
            var workshop = await _workshopRepository.GetAsync(id);
            return ObjectMapper.Map<Workshop, WorkshopDTO>(workshop);
        }

        /// <summary>
        /// 根据查询条件分页获取车间列表
        /// </summary>
        /// <param name="input">包含分页和筛选条件的对象</param>
        /// <returns>返回分页的车间列表</returns>
        public async Task<PagedResultDto<WorkshopDTO>> GetListAsync(GetWorkshopInputDto input)
        {
            // 1. 从仓储获取IQueryable<Workshop>以构建动态查询
            var queryable = await _workshopRepository.GetQueryableAsync();

            IQueryable<Workshop> query = queryable;
            
            // 2. 应用筛选条件
            if (!string.IsNullOrWhiteSpace(input.WorkshopCode))
            {
                query = query.Where(x => x.WorkshopCode.Contains(input.WorkshopCode));
            }

            if (!string.IsNullOrWhiteSpace(input.WorkshopName))
            {
                query = query.Where(x => x.WorkshopName.Contains(input.WorkshopName));
            }
            
            // 3. [关键] 修正分页参数
            // Layui传来的SkipCount是1-based的页码(page)，需转换为0-based的skip count
            var skipCount = 0;
            if (input.SkipCount > 0)
            {
                skipCount = (input.SkipCount - 1) * input.MaxResultCount;
            }
            
            // 4. 设置默认排序
            if (string.IsNullOrWhiteSpace(input.Sorting))
            {
                input.Sorting = "Id desc"; // 默认按Id倒序
            }
            
            // 5. 获取筛选后的总记录数
            var totalCount = await AsyncExecuter.CountAsync(query);
            
            // 6. 应用排序和分页，执行查询
            var items = await AsyncExecuter.ToListAsync(
                query.OrderBy(input.Sorting)
                     .Skip(skipCount)
                     .Take(input.MaxResultCount)
            );
            
            // 7. 将实体列表映射到DTO列表
            var dtoList = ObjectMapper.Map<List<Workshop>, List<WorkshopDTO>>(items);
            
            // 8. 返回标准分页结果
            return new PagedResultDto<WorkshopDTO>(totalCount, dtoList);
        }

        /// <summary>
        /// 创建一个新的车间
        /// </summary>
        /// <param name="input">用于创建车间的DTO对象</param>
        /// <returns>返回新创建的车间DTO</returns>
        public async Task<WorkshopDTO> CreateAsync(CreateUpdateWorkshopDto input)
        {
            // 使用AutoMapper将DTO映射到实体
            var workshop = ObjectMapper.Map<CreateUpdateWorkshopDto, Workshop>(input);
            // 插入到数据库
            var result = await _workshopRepository.InsertAsync(workshop);
            // 将返回的、包含新ID的实体映射回DTO
            return ObjectMapper.Map<Workshop, WorkshopDTO>(result);
        }

        /// <summary>
        /// 根据ID更新一个已有的车间
        /// </summary>
        /// <param name="id">要更新的车间实体的ID</param>
        /// <param name="input">包含更新信息的DTO对象</param>
        /// <returns>返回更新后的车间DTO</returns>
        public async Task<WorkshopDTO> UpdateAsync(int id, CreateUpdateWorkshopDto input)
        {
            // 获取现有实体
            var workshop = await _workshopRepository.GetAsync(id);
            // 将输入的DTO属性更新到实体上
            ObjectMapper.Map(input, workshop);
            // 更新到数据库
            var result = await _workshopRepository.UpdateAsync(workshop);
            // 将更新后的实体映射回DTO
            return ObjectMapper.Map<Workshop, WorkshopDTO>(result);
        }

        /// <summary>
        /// 根据ID删除一个车间
        /// </summary>
        /// <param name="id">要删除的车间实体的ID</param>
        public async Task DeleteAsync(int id)
        {
            await _workshopRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 批量删除车间
        /// </summary>
        /// <param name="ids">要删除的车间ID的集合</param>
        public async Task DeleteManyAsync(IEnumerable<int> ids)
        {
            await _workshopRepository.DeleteManyAsync(ids);
        }
    }
}
